<template>
  <div class="invoice-list">
    <el-form ref="searchForm" :model="queryForm" inline>
      <el-form-item label="单据编号">
        <el-input v-model="queryForm.number" placeholder="请输入单据编号" />
      </el-form-item>
      <el-form-item label="商品信息">
        <el-input v-model="queryForm.productInfo" placeholder="请输入条码、名称、规格、型号、颜色、扩展" />
      </el-form-item>
      <el-form-item label="单据日期">
        <el-date-picker v-model="queryForm.startDate" type="date" placeholder="开始时间" format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss" />
        <el-date-picker v-model="queryForm.endDate" type="date" placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getAll()">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="dialogVisible = true">+ 新增</el-button>
    <el-button type="" @click="handleDelete()">删除</el-button>
    <el-button type="" @click="examine(1)">审核</el-button>
    <el-button type="" @click="examine(9)">反审核</el-button>
    <el-button type="" @click="onSearch">导出</el-button>
    <el-button type="" @click="onSearch">列设置</el-button>
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" row-key="id" border
      default-expand-all>
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column prop="action" label="操作" width="180">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="handleEdit(row)" style="width: 20px;">查看</el-button>
          <el-button type="text" size="small" @click="handleEdit(row)" style="width: 20px;">编辑</el-button>
          <el-button type="text" size="small" @click="handleEdit(row)" style="width: 20px;">复制</el-button>
          <el-button type="text" size="small" @click="deleteOne(row.id)" style="width: 20px;">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="supplier" label="供应商" />
      <el-table-column prop="number" label="单据编号" />
      <el-table-column prop="name" label="商品信息" />
      <el-table-column prop="operTime" label="单据日期" />
      <el-table-column prop="creator" label="操作员" width="70" />
      <el-table-column prop="operNumber" label="数量" width="60" />
      <el-table-column prop="totalPrice" label="金额合计" width="100" />
      <el-table-column prop="taxLastMoney" label="含税合计" width="100" />
      <el-table-column prop="deposit" label="支付订金" width="100" />
      <el-table-column prop="purchaseStatus" label="状态" #default="scope">
        <el-button>
          <span v-if="scope.row.status == 0" style="color: red;">未审核</span>
          <span v-if="scope.row.status == 1" style="color: green;">已审核</span>
          <span v-if="scope.row.status == 2" style="color: cyan;">完成采购</span>
          <span v-if="scope.row.status == 3" style="color: blue;">部分采购</span>
          <span v-if="scope.row.status == 9" style="color: orange;">审核中</span>
        </el-button>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="新增" width="">
      <el-form ref="form" :model="addForm" label-width="120px">
        <el-form-item label="供应商">
          <el-select v-model="addForm.organId" placeholder="选择供应商">
            <el-option v-for="item in options" :key="item.id" :label="item.supplier" :value="item.id" />
            <!-- 更多供应商选项 -->
          </el-select>
        </el-form-item>
        <el-form-item label="商品">
          <el-select v-model="addForm.materialId" placeholder="选择商品">
            <el-option v-for="item in Material" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="单据日期">
          <el-col :span="11">
              <el-date-picker
                  clearable
                  v-model="addForm.operTime"
                  type="datetime"
                  placeholder="起始日期"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-col>

        </el-form-item> -->

        <el-form-item label="单据编号">
          <el-input v-model="addForm.number" placeholder="请输入单据编号" readonly />
        </el-form-item>

        <!-- <el-form-item label="关联订单">
          <el-select v-model="form关联订单" placeholder="请选择关联销售订单">
            <el-option label="订单1" value="order1" />
            <el-option label="订单2" value="order2" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="采购数量">
          <el-input-number v-model="addForm.operNumber" :min="1"  /> </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="addForm.remark" placeholder="请输入备注" :rows="2" />
        </el-form-item>

        <el-form-item label="结算账户">
          <el-input v-model="addForm.settlementAccount" placeholder="请输入结算账户" />
        </el-form-item>

        <el-form-item label="优惠率">
          <el-input v-model="addForm.discount" placeholder="请输入优惠率" />
        </el-form-item>
        <el-form-item label="优惠金额">
          <el-input v-model="addForm.discountMoney" placeholder="请输入优惠金额" />
        </el-form-item>
        <el-form-item label="优惠后金额">
          <el-input v-model="addForm.discountLastMoney" placeholder="请输入优惠后金额" />
        </el-form-item>
        <el-form-item label="订金">
          <el-input v-model="addForm.deposit" placeholder="请输入订金" />
        </el-form-item>

        <!-- <el-form-item label="条码">
          <el-input v-model="addForm.barcode" placeholder="输入条码或名称" />
          <el-button type="primary" icon="el-icon-upload">扫码录入</el-button>
        </el-form-item> -->

        <el-form-item label="附件">
          <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3"
            :on-exceed="handleExceed" :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="addCGDD()">保存</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
        :page-sizes="[1, 5, 10, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElTable, ElMessage, ElTableColumn, ElPagination, ElDatePicker } from 'element-plus';
import { purchaseOrderList,addPurchaseCGDD,materialList, supplierGYSList, deleteOrder } from '../../api/order/index.js'
const currentDate = ref(new Date());

const addForm = ref({
  // operTime: currentDate,
  operNumber:'',
  number: '',
  关联订单: '',
  remark: '',
  settlementAccount: '',
  discountRate: '',
  barcode: ''
});
// 生成 6 位随机数字
const generateRandomNumber = () => {
  return Math.floor(100000 + Math.random() * 900000).toString().padStart(6, '0');
};

onMounted(() => {
  addForm.value.number = `CGDD00000${generateRandomNumber()}`;
});

let ids = []
const handleSelectionChange = (val) => {
  ids = []
  val.forEach(ele => {
    ids.push(ele.id)
  });
  console.log(ids);
}
const options = ref([])
const Material = ref([])
const fileList = ref([]);

const onSubmit = () => {
  console.log('表单提交', form.value);
  ElMessage.success('表单提交成功！');
};

const onCancel = () => {
  dialogVisible.value = false
  ElMessage.warning('取消操作！');
};
//添加采购订单
function addCGDD() {
  console.log(addForm.value);
  addPurchaseCGDD(addForm.value).then(res=>{
    if (res.data.code == 200) {
      ElMessage.success("操作成功")
      dialogVisible.value = false
      getAll()
    }else{
      ElMessage.error("操作失败")
    }
  })
}

const handlePreview = (file) => {
  console.log('预览文件', file);
};

const handleRemove = (file, fileList) => {
  console.log('移除文件', file, fileList);
};

const beforeRemove = (file, fileList) => {
  return confirm(`确定要移除 ${file.name}？`);
};

const handleExceed = (files, fileList) => {
  ElMessage.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
};
// 搜索表单数据

const dialogVisible = ref(false)

// 表格数据
const tableData = ref([]);
// 总记录数
const total = ref();

// 当前页码
const queryForm = ref({
  invoiceNumber: '',
  productInfo: '',
  startDate: '',
  endDate: '',
  pageNum: 1,
  pageSize: 10
})
const handleSizeChange = (val) => {
  queryForm.value.pageSize = val
  getAll()
}
const handleCurrentChange = (val) => {
  queryForm.value.pageNum = val
  getAll()
}

// 搜索处理函数
const onSearch = () => {
  console.log('执行搜索操作', searchForm.value);
};

// 重置处理函数
const onReset = () => {
  console.log('执行重置操作');
};

// 编辑处理函数
const handleEdit = (row) => {
  console.log('执行编辑操作', row);
};
//审核
function examine(status) { }
//单删除
function deleteOne(id) {
  ids.push(id)
  if (confirm("确定要删除吗？")) {
    deleteOrder(ids).then(res => {
      if (res.data.code == 200) {
        ElMessage.success("操作成功")
        getAll()
      } else {
        ElMessage.error("操作失败")
        getAll()
      }
    })
  }
}
// 删除处理函数
const handleDelete = () => {
  console.log('执行删除操作', ids);
  if (confirm("确定要删除吗？")) {
    deleteOrder(ids).then(res => {
      if (res.data.code == 200) {
        ElMessage.success("操作成功")
        getAll()
      } else {
        ElMessage.error("操作失败")
        getAll()
      }
    })
  }
};

//查询所有采购订单
function getAll() {
  purchaseOrderList(queryForm.value,"CGDD").then(res => {
    if (res.data.code == 200) {
      tableData.value = res.data.data
      total.value = res.data.total
    }
  })
}
//查询所有供应商
function getSupplier() {
  supplierGYSList().then(res => {
    if (res.data.code == 200) {
      console.log(res.data.data);
      options.value = res.data.data
    }
  })
}
//查询所有商品
function getMaterial() {
  materialList().then(res => {
    if (res.data.code == 200) {
      console.log(res.data.data);
      Material.value = res.data.data
    }
  })
}

getSupplier()
getMaterial()
getAll()

</script>

<style scoped>
.invoice-list {
  margin: 20px;
}

.upload-demo {
  margin-bottom: 20px;
}
</style>